<template>
  <!-- 核销管理-待核销案件池 -->
  <section class="page wait-case-verify-pool">
    <data-form :model="searchModel" :page="pageService" @onSearch="refreshData" @handleResetForm="handleResetForm">
      <template slot="inputs">
        <el-form-item label="借据号" prop="caseNumber">
          <el-input v-model="searchModel.caseNumber"></el-input>
        </el-form-item>
        <el-form-item label="批次号" prop="verifyBatchNumber">
          <el-input v-model="searchModel.verifyBatchNumber"></el-input>
        </el-form-item>
        <el-form-item label="客户编号" prop="personalNo">
          <el-input v-model="searchModel.personalNo"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名" prop="personalName">
          <el-input v-model="searchModel.personalName"></el-input>
        </el-form-item>
        <el-form-item label="核销状态" prop="verifyStatus">
          <el-select v-model="searchModel.verifyStatus" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('VerifyStatus').filter(x=> x.name !== '已核销')" :key="index" :label="name" :value="code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件金额" prop="overdueAmount">
          <number-range v-model="searchModel.overdueAmount" :isInteger="true"></number-range>
        </el-form-item>
        <el-form-item label="逾期阶段" prop="overduePeriod">
          <el-select v-model="searchModel.overduePeriod" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('OverduePeriodStatus')" :key="index" :label="name" :value="code.replace(/M|\+/, '')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="逾期天数" prop="overdueDays">
          <number-range v-model="searchModel.overdueDays" :isInteger="true"></number-range>
        </el-form-item>
        <el-form-item label="系统来源" prop="sysCode">
          <el-select v-model="searchModel.sysCode" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('SysCode')" :key="index" :label="name" :value="code.replace(/M|\+/, '')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="searchModel.productName"></el-input>
        </el-form-item>
        <el-form-item label="放款渠道" prop="loanChannel">
          <el-select v-model="searchModel.loanChannel" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('LoanChannel')" :key="index" :label="name" :value="code.replace(/M|\+/, '')"></el-option>
          </el-select>
        </el-form-item>
      </template>
    </data-form>
    <data-box :data="dataSet" :page="pageService" :reserveSelection="true" ref="data-box"  @onPageChange="refreshData" :selectionList.sync="selectionList">
      <template slot="buttons">
        <el-button @click="badDebtConfirmClick" v-auth = "1902">坏账确认</el-button>
        <el-button @click="cancelCaseClick" v-auth = "1903">撤销申请</el-button>
        <el-button @click="badDebtConfirmClickAgain" v-auth = "1904">重新提交</el-button>
        <el-button @click="applyFlowClick">申请流转</el-button>
        <el-button @click="downloadVerifiedCase" v-auth = "1904">导出案件</el-button>
      </template>
      <template slot="columns">
        <el-table-column prop="verifyBatchNumber" label="申请批次号" :min-width="$helper.getColumnWidth(6)">
        </el-table-column>
        <el-table-column prop="caseNumber" label="借据号" :min-width="$helper.getColumnWidth(6)" show-overflow-tooltip>
          <template slot-scope="scope">
            <a  @click="openExecutionPage(scope.row)">{{scope.row.caseNumber}}</a>
          </template>
        </el-table-column>
        <el-table-column prop="personalName" label="客户姓名" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="personalNo" label="客户编号" :min-width="$helper.getColumnWidth(3)" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="area" label="地区" :min-width="$helper.getColumnWidth(4)" :formatter="(row) => $city.getInheritNames(Number(row.area))" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="overdueAmount" label="案件金额(元)" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="overduePeriod" label="逾期阶段" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="overdueDays" label="逾期天数" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="sysCode" label="系统来源" :min-width="$helper.getColumnWidth(4)" :formatter="(row) => $filter.encryptSysCode(row.sysCode)">
        </el-table-column>
        <el-table-column prop="loanChannel" label="放款渠道" :min-width="$helper.getColumnWidth(4)" :formatter="(row) => $filter.encryptLoanChannel(row.loanChannel)">
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="perDueDate" label="还款日" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="commonFlag" label="附件是否提交" :min-width="$helper.getColumnWidth(4)" :formatter="(row) => $filter.dictConvert(row.commonFlag,'CommonFlag')">
        </el-table-column>
        <el-table-column prop="verifyStatus" label="核销状态" :min-width="$helper.getColumnWidth(4)" :formatter="(row) => $filter.dictConvert(row.verifyStatus,'VerifyStatus')">
        </el-table-column>
        <el-table-column prop="followInTime" label="案件流入时间" :formatter="(row) => $filter.dateTimeFormat(row.followInTime)" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
      </template>
    </data-box>

    <!-- 坏账确认/重新提交 -->
    <el-dialog :title="titleChange" :center="true" width="1200px" :visible.sync="dialog.isOpenCaseConfirmation" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <bad-debts-confirmation :applyRecordDescription="applyRecordDescription" :totalBadAmount="totalBadAmount" :BadAmountBase='BadAmountBase' :applyRecordfileList="applyRecordfileList" :BaseVerifyBatchNumber="BaseVerifyBatchNumber" :BaseVerifyStatus="BaseVerifyStatus" ref="bad-debts-confirmation" @close="badDebtsConfirmationClose()" @refreshData="refreshData" :selectionList="selectionList"></bad-debts-confirmation>
    </el-dialog>
    <!--申请弹框-->
    <el-dialog title="流转申请" width="800px" :visible.sync="dialog.apply" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <apply :caseIds="selectedCaseIds" :fromChannel="caseChannel" :applyType="applyType.value" @close="onApplyClose" ref="apply-circulation"></apply>
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Auth, Layout, Dependencies } from "~/core/decorator";
import { PageService } from "~/utils/page.service";
import DataForm from "~/components/common/data-form.vue";
import DataBox from "~/components/common/data-box.vue";
import NumberRange from "~/components/common/number-range.vue";
import { CaseVerifyService } from "~/services/domain-service/case-verify.service";
import { Getter,namespace } from 'vuex-class';
import BadDebtsConfirmation from '~/components/case-verify-manage/bad-debts-confirmation.vue';
import { CaseApplyRecordService } from "~/services/domain-service/case-apply-record.service";
import { ApplyType, CASE_CHANNEL } from '~/config/enum.config';
import { OpenExecutionData } from "~/config/types";
import Apply from '~/components/visit-case/apply.vue';
const CollectionExecutionModule = namespace("collection-execution");

@Layout("workspace")
@Component({
  components: {
    DataForm,
    DataBox,
    NumberRange,
    BadDebtsConfirmation,
    Apply
  }
})
export default class WaitCaseVerifyPool extends Vue {
  @Dependencies(PageService)
  private pageService: PageService;
  @Dependencies(CaseVerifyService)
  private caseVerifyService: CaseVerifyService;
  @Dependencies(CaseApplyRecordService) private caseApplyRecordService: CaseApplyRecordService;
  @CollectionExecutionModule.Action
  private openCollectionExecution;
  // 数据
  private dataSet: any[] = []
  private BadAmountBase: any[] = []
  private applyType = ApplyType.turn
  private selectionList: any = []
  private BaseVerifyBatchNumber: any = ''
  private BaseVerifyStatus: any = ''
  private rowData: any = null
  private applyRecordfileList: any = []
  private applyRecordDescription: any = ''
  private titleChange: any = ''
  private totalBadAmount: any = ''
  private totalOverdueAmount: any = ''
  private totalBadAmountCaseIds: any[] = []
  private caseChannel = CASE_CHANNEL.verify;
  private searchModel: any = {
    caseNumber: "",
    personalName: "",
    personalNo:'',
    mobileNo: "",
    idCard: "",
    customerCategory: "",
    sysCode: "",
    loanChannel: "",
    productName: "",
    overdueAmount: {
      max: "",
      min: ""
    },
    overduePeriod: "",
    overdueDays: {
      max: "",
      min: ""
    },
    followInTime: "",
    area: [],
    turnSource: "",
    commonFlag: "",
    verifyStatus: "",
  };
  // 弹框控制
  private dialog: any = {
    isOpenCaseConfirmation: false,
    apply:false
  };
  private applyFlowClick() {
    if (this.selectionList.length === 0) {
      this.$message(`请选择要申请流转的案件`);
      return;
    }
    this.dialog.apply = true;
  }
  private onApplyClose() {
    this.dialog.apply = false;
    this.refreshData()
  }
  private get selectedCaseIds() {
    return this.selectionList.map((v) => v.id);
  }
  private mounted() {
    this.refreshData()
  }
  private refreshData() {
    this.caseVerifyService.getAllVerifyInfos(this.searchModel, this.pageService).subscribe(
      data => {
        this.dataSet = data
        if(this.dataSet){
          this.dataSet.forEach(x=>{
            x.overduePeriod>12?x.overduePeriod = 'M12+':x.overduePeriod = 'M'+x.overduePeriod
          })
        }
      }
    )
  }
  /**
   * 进入查看执行页
   */
  private openExecutionPage(row) {
    this.openCollectionExecution(
      new OpenExecutionData(
        row.id,
        row.caseNumber,
        CASE_CHANNEL.undistributed,
        true,
        true
      )
    );
  }

  /**
   * 撤销申请
   */
  private cancelCaseClick(){
    if (this.selectionList.length === 0) {
      this.$message.info("请先选择要撤销的案件")
      return
    }
    if( this.selectionList.find(v => v.verifyStatus !== "UNDER_REVIEW")) {
      this.$alert("只能撤回未审批的案件，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    //多选时对批次号进行判断是否一致
    this.BaseVerifyBatchNumber = this.selectionList[0].verifyBatchNumber
    if( this.selectionList.length>1&&this.selectionList.find(v => v.verifyBatchNumber !== this.BaseVerifyBatchNumber)) {
      this.$alert("选择的案件存在批次号不一致，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    this.caseApplyRecordService.approvalWithdraw(this.BaseVerifyBatchNumber).subscribe(
        data => {
          this.$message.success("撤销成功")
          this.refreshData()
        }
      )
  }

  /**
   * 坏账确认
   */
  private async badDebtConfirmClick() {
    this.totalBadAmountCaseIds = []
    if (this.selectionList.length === 0) {
      this.$message.info("请先选择要确认的案件")
      return
    }
    if( this.selectionList.find(v => v.verifyStatus === "VERIFIED"||v.verifyStatus === "UNDER_REVIEW")) {
      this.$alert("选择的案件存在已坏账确认的案件，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    if( this.selectionList.find(v => v.verifyStatus === "DISMISSED")) {
      this.$alert("选择的案件存在被驳回的案件，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    //多选时对批次号进行判断是否一致
    this.BaseVerifyBatchNumber = this.selectionList[0].verifyBatchNumber
    this.BaseVerifyStatus = this.selectionList[0].verifyStatus
    if( this.selectionList.length>1&&this.selectionList.find(v => v.verifyBatchNumber !== this.BaseVerifyBatchNumber)) {
      this.$alert("选择的案件存在批次号不一致，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    //获取所有选择的caseId
    this.selectionList.map(x=>{
      this.totalBadAmountCaseIds.push(x.id)
    })
    this.getBadAmount(this.totalBadAmountCaseIds)
    this.getTotalOverdueAmount(this.totalBadAmountCaseIds)
    this.getBadAmountBaseData(this.totalBadAmountCaseIds)
    this.titleChange = '坏账确认'
    this.dialog.isOpenCaseConfirmation = true
  }
  // 坏账确认弹框关闭
  private badDebtsConfirmationClose(){
    this.dialog.isOpenCaseConfirmation=false
    this.selectionList = []
    this.refreshData()
    const dataBox: any = this.$refs['data-box']
    dataBox.clearSelection()
  }
  /**
   * 重新提交
   */
  private async badDebtConfirmClickAgain() {
    this.totalBadAmountCaseIds = []
    if (this.selectionList.length === 0) {
      this.$message.info("请先选择要重新提交的案件")
      return
    }
    if( this.selectionList.find(v => v.verifyStatus === "VERIFIED"||v.verifyStatus === "UNDER_REVIEW")) {
      this.$alert("选择的案件存在已坏账确认的案件，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    if( this.selectionList.find(v => v.verifyStatus === "WAIT_VERIFY")) {
      this.$alert("状态为待核销状态的案件只能坏账确认", "提示", {confirmButtonText: '确定'})
      return
    }
    //多选时对批次号进行判断是否一致
    this.BaseVerifyBatchNumber = this.selectionList[0].verifyBatchNumber
    this.BaseVerifyStatus = this.selectionList[0].verifyStatus
    if( this.selectionList.length>1&&this.selectionList.find(v => v.verifyBatchNumber !== this.BaseVerifyBatchNumber)) {
      this.$alert("选择的案件存在批次号不一致，请重新选择", "提示", {confirmButtonText: '确定'})
      return
    }
    //获取所有选择的caseId
    this.selectionList.map(x=>{
      this.totalBadAmountCaseIds.push(x.id)
    })
    this.getBadAmount(this.totalBadAmountCaseIds)
    this.getTotalOverdueAmount(this.totalBadAmountCaseIds)
    this.getBadAmountBaseData(this.totalBadAmountCaseIds)
    this.caseApplyRecordService.getVerApplyRecord(this.BaseVerifyBatchNumber).subscribe(
        data => {
          this.applyRecordfileList = data.uploadFileList
          this.applyRecordfileList.forEach(x=>{
            x.name = x.originalName
          })
          this.applyRecordDescription = data.applyDescription
        }
      )
    this.titleChange = '重新提交'
    this.dialog.isOpenCaseConfirmation = true
  }
  //统计坏账金额钱数
  private getBadAmount(data){
    this.caseApplyRecordService.getBadAmount(data).subscribe(
      data => {
        this.totalBadAmount = data
      }
    )
  }
  //统计案件金额总数
  private getTotalOverdueAmount(data){
    this.caseApplyRecordService.getTotalOverdueAmount(data).subscribe(
      data => {
        this.totalOverdueAmount = data
      }
    )
  }
  //统计坏账金额数据
  private getBadAmountBaseData(data){
    const request: any = {
      caseIds: data,
    }
    this.caseVerifyService.getWaitVerifyConfirmInfos(request,this.pageService).subscribe(
      data => {
        this.BadAmountBase = data
        if(this.BadAmountBase){
          this.BadAmountBase.forEach(x=>{
            x.overduePeriod>12?x.overduePeriod = 'M12+':x.overduePeriod = 'M'+x.overduePeriod
          })
        }
      }
    )
  }
  /**
   * 需要手动重置的表单项
   */
  private handleResetForm() {
    this.searchModel.overdueAmount = { max: "", min: "" }
    this.searchModel.overdueDays = { max: "", min: ""}
  }
  /**
   * 导出待核销案件
   */
  private downloadVerifiedCase(){
    if(this.dataSet.length === 0){
      this.$message("暂无数据可以导出")
      return
    }
    const ids =this.selectionList? this.selectionList.map((v) => v.id):'';
    const request: any = {
      ...this.searchModel,
      caseIds: ids,
    }
    this.caseVerifyService.exportWaitVerifyInfos(request).subscribe(
      data=>{
        this.$common.downloadFile(data.url,'待核销案件.xls')
      }
    )
  }

}
</script>

<style lang="less">
</style>
